﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Runtime.InteropServices;


namespace WebDummy
{
    public class Fetch
    {
        

        protected static String Page;
        public static String Response;
        
        public static CookieContainer Cookies = new CookieContainer();

        public Fetch(String URL)
        {
            Page = URL;
            
        }

        public static string FetchPage(String page = "")
        {
            if (!page.Equals(""))
                Page = page;
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Page);
            makeHeadersGet(myRequest);
            myRequest.CookieContainer = Cookies;

            WebResponse myResponse = myRequest.GetResponse();
            //Cookies = myRequest.CookieContainer;
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = sr.ReadToEnd();
            Response = result;
            //String LoginForm = Response.Substring(Response.IndexOf(FormStart,Response.in));

            sr.Close();
            myResponse.Close();

            return Response;
        }
        protected bool PostData(String Parameters,String page= "")
        {
            if (!Page.Equals(""))
                Page = page;

            HttpWebRequest Req = (HttpWebRequest)WebRequest.Create(Page);
            CookieContainer Transfer = new CookieContainer();
            Req.CookieContainer = Transfer;
            makeHeadersPost(Req);
            
            // Create POST data and convert it to a byte array.
            string postData = Parameters;
          
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            Req.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            Req.ContentLength = byteArray.Length;

            Stream PostData = Req.GetRequestStream();
            //Now we write, and afterwards, we close. Closing is always important!
            PostData.Write(byteArray, 0, byteArray.Length);
            PostData.Close();
            HttpWebResponse WebResp = (HttpWebResponse)Req.GetResponse();
            foreach (Cookie Cookie in WebResp.Cookies)
            {
                Cookies.Add(Cookie);
            }
            //Let's show some information about the response
            Console.WriteLine(WebResp.StatusCode);
            Console.WriteLine(WebResp.Server);

            //Now, we read the response (the string), and output it.
            Stream Answer = WebResp.GetResponseStream();
            StreamReader _Answer = new StreamReader(Answer);
            String _StrAnswer = _Answer.ReadToEnd();
            if (_StrAnswer.Contains(Page))
                return false;
            return true;
        }

        private static void makeHeadersGet(HttpWebRequest myRequest)
        {
            makeHeaders(myRequest);
            
            myRequest.Method = "GET";
            myRequest.Proxy = WebRequest.GetSystemWebProxy();
        }

        private static void makeHeadersPost(HttpWebRequest myRequest)
        {
            makeHeaders(myRequest);
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.Method = "POST";
        }

        private static void makeHeaders(HttpWebRequest myRequest)
        {
            myRequest.UserAgent = "Mozilla/5.0 (Ubuntu; X11; Linux x86_64; rv:8.0) Gecko/20100101 Firefox/8.0";
            myRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            myRequest.KeepAlive = true;
            HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Refresh);
            myRequest.CachePolicy = policy;
            myRequest.ContentType = "text/html";
            
            myRequest.Proxy = WebRequest.GetSystemWebProxy();
        }

        public static String Download(String Webpage, String path)
        {

            WebClient client = new WebClient();
            List<String> Line = new List<String>();
            //Checks if file exists, and deletes if exists
            if (File.Exists(path))
            {
                if ((File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.ReadOnly)
                {
                    File.SetAttributes(path, FileAttributes.Normal);
                }
                File.Delete(path);
            }
            //download the file to the specified location, using HTTP  
            client.DownloadFile(Webpage, path);


            //"`" replacement in DB.ExecuteSQLFile
           
                //StreamReader sr = new StreamReader(path);

                //string line;

                ////loop thru the lines in the file  
                //while ((line = sr.ReadLine()) != null)
                //{
                //    //Remove the back tick from the name of the table, because this only  
                //    //works with MySQL, in SQL Server this throws an error  
                //    line = line.Replace("`", "");
                //}
            
            return path;
        }
    }
}
